<template>
  <div class="announcement-management">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" inline>
        <el-form-item label="公告标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入公告标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="公告类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择公告类型"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in utils.getTypeOptions()"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公告级别">
          <el-select
            v-model="searchForm.level"
            placeholder="请选择公告级别"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in utils.getLevelOptions()"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="公告状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择公告状态"
            clearable
            style="width: 150px"
          >
            <el-option
              v-for="option in utils.getStatusOptions()"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card" shadow="never">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            新增公告
          </el-button>
          <el-button
            type="warning"
            :disabled="selectedIds.length === 0"
            @click="handleBatchOperation"
          >
            <el-icon><Operation /></el-icon>
            批量操作
          </el-button>
          <el-button type="info" @click="handleViewStatistics">
            <el-icon><DataAnalysis /></el-icon>
            统计信息
          </el-button>
        </div>
        <div class="right-operations">
          <el-dropdown @command="handleMaintenanceCommand">
            <el-button type="success">
              <el-icon><Tools /></el-icon>
              维护操作
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="auto-expire"
                  >自动过期公告</el-dropdown-item
                >
                <el-dropdown-item command="clean-deleted"
                  >清理已删除公告</el-dropdown-item
                >
                <el-dropdown-item command="clean-read-records"
                  >清理阅读记录</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column
          prop="title"
          label="公告标题"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="utils.getTypeTagType(row.type)">
              {{ utils.getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="{ row }">
            <el-tag :type="utils.getLevelTagType(row.level)">
              {{ utils.getLevelText(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="utils.getStatusTagType(row.status)">
              {{ utils.getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="特殊标记" width="120">
          <template #default="{ row }">
            <div class="special-marks">
              <el-tag v-if="row.isTop" type="warning" size="small">置顶</el-tag>
              <el-tag v-if="row.isPopup" type="danger" size="small"
                >弹窗</el-tag
              >
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="targetAudienceName"
          label="目标受众"
          width="100"
        />
        <el-table-column prop="viewCount" label="浏览次数" width="100">
          <template #default="{ row }">
            {{ utils.formatViewCount(row.viewCount) }}
          </template>
        </el-table-column>
        <el-table-column label="剩余天数" width="120">
          <template #default="{ row }">
            <span
              :class="{
                'text-danger': row.remainingDays <= 3 && row.remainingDays > 0,
                'text-warning': row.remainingDays <= 7 && row.remainingDays > 3
              }"
            >
              {{ utils.formatRemainingDays(row.remainingDays) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="创建者" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-dropdown
              @command="command => handleQuickOperation(command, row)"
            >
              <el-button type="info" size="small">
                操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="row.status === 0" command="publish">
                    发布
                  </el-dropdown-item>
                  <el-dropdown-item v-if="row.status === 1" command="archive">
                    存档
                  </el-dropdown-item>
                  <el-dropdown-item :command="row.isTop ? 'untop' : 'top'">
                    {{ row.isTop ? "取消置顶" : "置顶" }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    :command="row.isPopup ? 'unpopup' : 'popup'"
                  >
                    {{ row.isPopup ? "取消弹窗" : "设为弹窗" }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadData"
          @current-change="loadData"
        />
      </div>
    </el-card>

    <!-- 公告编辑对话框 -->
    <AnnouncementEditDialog
      v-model:visible="editDialogVisible"
      :announcement="currentAnnouncement"
      @success="handleEditSuccess"
    />

    <!-- 公告详情对话框 -->
    <AnnouncementDetailDialog
      v-model:visible="detailDialogVisible"
      :announcement="currentAnnouncement"
    />

    <!-- 批量操作对话框 -->
    <BatchOperationDialog
      v-model:visible="batchDialogVisible"
      :selected-ids="selectedIds"
      @success="handleBatchSuccess"
    />

    <!-- 统计信息对话框 -->
    <StatisticsDialog v-model:visible="statisticsDialogVisible" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Refresh,
  Plus,
  Operation,
  DataAnalysis,
  Tools,
  ArrowDown
} from "@element-plus/icons-vue";
import {
  getAdminAnnouncementListApi,
  deleteAnnouncementApi,
  publishAnnouncementApi,
  archiveAnnouncementApi,
  toggleTopAnnouncementApi,
  togglePopupAnnouncementApi,
  autoExpireAnnouncementsApi,
  cleanDeletedAnnouncementsApi,
  cleanReadRecordsApi,
  AnnouncementManagementUtils,
  type AnnouncementInfo,
  type AnnouncementListQuery
} from "@/api/announcement-management";
import AnnouncementEditDialog from "./components/AnnouncementEditDialog.vue";
import AnnouncementDetailDialog from "./components/AnnouncementDetailDialog.vue";
import BatchOperationDialog from "./components/BatchOperationDialog.vue";
import StatisticsDialog from "./components/StatisticsDialog.vue";

// 将工具类暴露给模板
const utils = AnnouncementManagementUtils;

// 响应式数据
const loading = ref(false);
const tableData = ref<AnnouncementInfo[]>([]);
const selectedIds = ref<number[]>([]);
const tableRef = ref();

// 搜索表单
const searchForm = reactive<AnnouncementListQuery>({
  title: "",
  type: undefined,
  level: undefined,
  status: undefined
});

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 对话框状态
const editDialogVisible = ref(false);
const detailDialogVisible = ref(false);
const batchDialogVisible = ref(false);
const statisticsDialogVisible = ref(false);
const currentAnnouncement = ref<AnnouncementInfo | null>(null);

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: pagination.current,
      size: pagination.size
    };

    const response = await getAdminAnnouncementListApi(params);
    if (response && response.code === 200 && response.data) {
      tableData.value = response.data.records;
      pagination.total = response.data.total;
      pagination.current = response.data.current;
      pagination.size = response.data.size;
    }
  } catch (error: any) {
    console.error("加载公告列表失败:", error);
    ElMessage.error(`加载公告列表失败: ${error?.message || "未知错误"}`);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    title: "",
    type: undefined,
    level: undefined,
    status: undefined
  });
  pagination.current = 1;
  loadData();
};

// 表格选择变化
const handleSelectionChange = (selection: AnnouncementInfo[]) => {
  selectedIds.value = selection.map(item => item.id);
};

// 新增公告
const handleAdd = () => {
  currentAnnouncement.value = null;
  editDialogVisible.value = true;
};

// 编辑公告
const handleEdit = (row: AnnouncementInfo) => {
  currentAnnouncement.value = row;
  editDialogVisible.value = true;
};

// 查看公告
const handleView = (row: AnnouncementInfo) => {
  currentAnnouncement.value = row;
  detailDialogVisible.value = true;
};

// 删除公告
const handleDelete = async (row: AnnouncementInfo) => {
  try {
    await ElMessageBox.confirm(`确定要删除公告"${row.title}"吗？`, "删除确认", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消"
    });

    const response = await deleteAnnouncementApi(row.id);
    if (response && response.code === 200) {
      ElMessage.success("删除成功");
      loadData();
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除公告失败:", error);
      ElMessage.error(`删除失败: ${error?.message || "未知错误"}`);
    }
  }
};

// 快速操作
const handleQuickOperation = async (command: string, row: AnnouncementInfo) => {
  try {
    let response;
    let successMessage = "";

    switch (command) {
      case "publish":
        response = await publishAnnouncementApi(row.id);
        successMessage = "发布成功";
        break;
      case "archive":
        response = await archiveAnnouncementApi(row.id);
        successMessage = "存档成功";
        break;
      case "top":
        response = await toggleTopAnnouncementApi(row.id, true);
        successMessage = "置顶成功";
        break;
      case "untop":
        response = await toggleTopAnnouncementApi(row.id, false);
        successMessage = "取消置顶成功";
        break;
      case "popup":
        response = await togglePopupAnnouncementApi(row.id, true);
        successMessage = "设为弹窗成功";
        break;
      case "unpopup":
        response = await togglePopupAnnouncementApi(row.id, false);
        successMessage = "取消弹窗成功";
        break;
    }

    if (response && response.code === 200) {
      ElMessage.success(successMessage);
      loadData();
    }
  } catch (error: any) {
    console.error("操作失败:", error);
    ElMessage.error(`操作失败: ${error?.message || "未知错误"}`);
  }
};

// 批量操作
const handleBatchOperation = () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要操作的公告");
    return;
  }
  batchDialogVisible.value = true;
};

// 查看统计信息
const handleViewStatistics = () => {
  statisticsDialogVisible.value = true;
};

// 维护操作
const handleMaintenanceCommand = async (command: string) => {
  try {
    let response;
    let successMessage = "";

    switch (command) {
      case "auto-expire":
        await ElMessageBox.confirm(
          "确定要执行自动过期操作吗？这将过期所有到期的公告。",
          "操作确认",
          { type: "warning" }
        );
        response = await autoExpireAnnouncementsApi();
        successMessage = "自动过期操作完成";
        break;
      case "clean-deleted":
        await ElMessageBox.confirm(
          "确定要清理已删除的公告吗？这将永久删除30天前的已删除公告。",
          "操作确认",
          { type: "warning" }
        );
        response = await cleanDeletedAnnouncementsApi();
        successMessage = "清理已删除公告完成";
        break;
      case "clean-read-records":
        await ElMessageBox.confirm(
          "确定要清理过期的阅读记录吗？这将删除90天前的阅读记录。",
          "操作确认",
          { type: "warning" }
        );
        response = await cleanReadRecordsApi();
        successMessage = "清理阅读记录完成";
        break;
    }

    if (response && response.code === 200) {
      ElMessage.success(successMessage);
      loadData();
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("维护操作失败:", error);
      ElMessage.error(`操作失败: ${error?.message || "未知错误"}`);
    }
  }
};

// 编辑成功回调
const handleEditSuccess = () => {
  editDialogVisible.value = false;
  loadData();
};

// 批量操作成功回调
const handleBatchSuccess = () => {
  batchDialogVisible.value = false;
  selectedIds.value = [];
  tableRef.value?.clearSelection();
  loadData();
};

// 组件挂载时加载数据
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.announcement-management {
  padding: 20px;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.left-operations,
.right-operations {
  display: flex;
  gap: 10px;
}

.special-marks {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-danger {
  font-weight: bold;
  color: #f56c6c;
}

.text-warning {
  font-weight: bold;
  color: #e6a23c;
}
</style>
